import postApi from '@/api/modules/post'
import { calculatePlayerScores, calculatePlayerScoresAsync } from '@/utils/scoreCalculator'

interface PlayerLike {
    player_id: string
    userid_platform?: string
    avatar?: string
    player_name?: string
    team?: string
    units?: number
    finalScore?: number
    score?: number
    game_id?: number
}

interface MessageLike {
    player_id?: string
    userid_platform?: string
    uuid?: string
    game_id?: number
    avatar?: string
    player_name?: string
    team?: string
}

interface PollPayload {
    leftPlayers: PlayerLike[]
    rightPlayers: PlayerLike[]
    messages: MessageLike[]
    pointPool: number
    anchorId: string
    gameId: number
    winTeam: string
    redName: string
    blueName: string
}

interface PlayerResult {
    uuid: string
    game_id: number
    userid_platform: string
    avatar: string
    player_name: string
    point: number
    team: string
    race: string
    units: number
    is_winner: boolean
    is_test: boolean
}

let isSyncing = false

const buildPlayerResults = async ({
    leftPlayers,
    rightPlayers,
    messages,
    winTeam,
    pointPool,
    anchorId,
    redName,
    blueName,
    gameId
}: PollPayload): Promise<PlayerResult[]> => {
    const allPlayers = [...(leftPlayers || []).map(player => ({ ...player, team: 'blue' })), ...(rightPlayers || []).map(player => ({ ...player, team: 'red' }))]

    let playersWithFinalScores: Array<PlayerLike & { team: string; finalScore: number }>
    try {
        playersWithFinalScores = await calculatePlayerScoresAsync(
            allPlayers,
            messages || [],
            winTeam,
            pointPool,
            'xinJi结算',
            false
        ) as Array<PlayerLike & { team: string; finalScore: number }>
    } catch (error) {
        console.error('[pollServerUpdates] Web Worker 积分计算失败，使用同步回退:', error)
        playersWithFinalScores = calculatePlayerScores(
            allPlayers,
            messages || [],
            winTeam,
            pointPool,
            'xinJi结算',
            false
        ) as Array<PlayerLike & { team: string; finalScore: number }>
    }

    const isTestAccount = anchorId === '111admin' || anchorId === '222admin'

    return playersWithFinalScores
        .map<PlayerResult | null>(player => {
            const playerMessages = (messages || []).filter(msg => msg.userid_platform === player.userid_platform)
            const baseMessage = playerMessages[0] || {}
            const userid =  player.userid_platform
            if (!userid) {
                return null
            }
            const finalScore = Number(player.finalScore || 0)
            if (finalScore <= 0) {
                return null
            }
            const team = player.team
            return {
                uuid: baseMessage.uuid || '',
                game_id: baseMessage.game_id || gameId || 1,
                userid_platform: userid,
                avatar: player.avatar || '',
                player_name: player.player_name || '',
                point: finalScore,
                team,
                race: team === 'red' ? redName : blueName,
                units: player.units || 0,
                is_winner: team === winTeam,
                is_test: isTestAccount,
            }
        })
        .filter((item): item is PlayerResult => Boolean(item))
}

export const pollServerUpdates = async (payload: PollPayload) => {
    if (isSyncing) return

    const {
        leftPlayers,
        rightPlayers,
        messages,
        pointPool,
        anchorId,
        gameId,
        winTeam,
        redName,
        blueName
    } = payload

    if (!Array.isArray(leftPlayers) || !Array.isArray(rightPlayers)) return
    if (!Array.isArray(messages) || messages.length === 0) return
    if (!gameId) return

    const playerResults = await buildPlayerResults({
        leftPlayers,
        rightPlayers,
        messages,
        pointPool,
        anchorId,
        gameId,
        winTeam,
        redName,
        blueName
    })

    if (!playerResults.length) return

    isSyncing = true
    try {
        await postApi.settleGame(playerResults)
        if (anchorId && pointPool > 0) {
            await postApi.updateAnchorData({
                anchor_id: anchorId,
                game_id: gameId,
                point_pool: Math.round(pointPool / 2)
            })
        }
    } catch (_) {
        // console.error('轮询同步失败:', error)
    } finally {
        isSyncing = false
    }
}
